package com.wen.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wen.mapper.TagMapper;
import com.wen.pojo.Tag;
import com.wen.pojo.Type;
import com.wen.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String list(Model model, @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum,4);
        List<Tag> tagList = tagService.getAllTag();
        PageInfo<Tag> pageInfo = new PageInfo<>(tagList);
        model.addAttribute("pageInfo",pageInfo);
        return "/admin/tags";
    }
    //跳转到新增标签tags-input
    @GetMapping("/tags/input")
    public String toAddTags(Model model){
        model.addAttribute("tag",new Tag());
        return "/admin/tags-input";
    }

    @PostMapping("tags")
    public String addTags(@Valid Tag tag, RedirectAttributes attributes){
        Tag tag1 = tagService.getTagByName(tag.getName());
        if (tag1 != null){
            attributes.addFlashAttribute("message","不能添加重复的类");
            return "redirect:/admin/tags/input";
        }
        int t = tagService.addTag(tag);
        if(t == 0){
            attributes.addFlashAttribute("message","新增失败");
        }else{
            attributes.addFlashAttribute("message","新增成功");
        }
        return "redirect:/admin/tags";
    }

    //跳转更新分类
    @GetMapping("/tags/{id}/input")
    public String toUpdate(@PathVariable Long id, Model model){
        model.addAttribute("tag",tagService.getTag(id));
        return "admin/tags-input";
    }

    //编辑修改页面（更新）
    @PostMapping("tags/{id}")
    public String editPost(@Valid Tag tag,RedirectAttributes attributes){
        Tag tag1 = tagService.getTagByName(tag.getName());
        if(tag1 != null){
            attributes.addFlashAttribute("message","不能添加重复的分类");
            return "redirect:/admin/tags/input";
        }
        int t = tagService.updateTag(tag);
        if(t==0){
            attributes.addFlashAttribute("message","编辑失败");
        }else{
            attributes.addFlashAttribute("message","编辑成功");
        }
        return "redirect:/admin/tags";
    }

    //删除分类
    @GetMapping("tags/{id}/delete")
    public String delete(@PathVariable long id,RedirectAttributes attributes){
        tagService.deleteTag(id);
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/tags";
    }



}
